package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapMergePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapMergePayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import io.swagger.v3.core.util.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    IPaymentInfoService paymentInfoService;

    @Override
    public String submitAlipay(String orderNo) {
        //1.先保存支付信息
        PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(orderNo);
        try {
            //2.调用支付接口：alipay.trade.wap.pay(手机网站支付接口2.0)
            AlipayTradeWapPayRequest alipayTradeWapMergePayRequest = new AlipayTradeWapPayRequest();
            //同步回调
            alipayTradeWapMergePayRequest.setReturnUrl(AlipayConfig.return_payment_url);
            //异步回调
            alipayTradeWapMergePayRequest.setNotifyUrl(AlipayConfig.notify_payment_url);
            HashMap<String, Object> map = new HashMap<>();
            map.put("out_trade_no", paymentInfo.getOrderNo());//商户订单号
            map.put("product_code", "QUICK_WAP_WAY");//销售产品码，商家和支付宝签约的产品码，为固定值QUICK_WAP_WAY
            map.put("total_amount", paymentInfo.getAmount());//订单总金额
            map.put("subject", paymentInfo.getContent());//订单内容或者交易内容
            // 获取当前时间并加上15分钟
            LocalDateTime expireTime = LocalDateTime.now().plusMinutes(15);
            // 格式化时间为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String expireTimeStr = expireTime.format(formatter);
//            map.put("time_expire", "2025-08-29 17:09:00");//订单过期时间
            map.put("time_expire",expireTimeStr);
            alipayTradeWapMergePayRequest.setBizContent(JSON.toJSONString(map));
            AlipayTradeWapPayResponse post = alipayClient.pageExecute(alipayTradeWapMergePayRequest, "post");//向支付宝发送请求并获取响应
            String h5Form = post.getBody();
            return h5Form;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw  new ServiceException("支付失败");
        }

    }
}
